package com.sky.common;


import com.sky.config.AliOSSAutoConfig;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Api("文件上传控制类")
@RestController
public class uploadFileController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/admin/common/upload")
    @ApiOperation("文件上传接口")
    public Result<String> upload(MultipartFile file){
        //拼接文件名，目录按照时间格式建立
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
        String format = formatter.format(now);
        String objectName = file.getOriginalFilename();
        String originalFilename = file.getOriginalFilename();
        String fileName = format + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //得到返回网址
        String url = aliOssUtil.upload(bytes, fileName);
        return Result.success(url);
    }
}
